package mqpaydemo.paydemo.pay.portal.rabbitMq;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import mqpaydemo.paydemo.pay.request.OrdersRequest;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:下单成功，发送mq去扣钱
 * @Author: liujinsheng
 * @Date: 2021/9/15. @Autowired
    private Environment env;

 */
@Component
@Slf4j
public class PaySend implements RabbitTemplate.ConfirmCallback {
    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    Environment env;

    public void send(OrdersRequest OrdersRequest){
        //要先在配置文件中配置交换机和路由和队列
        Map<String, Object> map=new HashMap();
        map.put("userId",OrdersRequest.getUserId());
        map.put("goodsId",OrdersRequest.getGoodsId());
        map.put("price",OrdersRequest.getPrice());

        log.info("要发送的消息{}",OrdersRequest.toString());
        try {
            //这个是绑定了交换机和指定队列
            rabbitTemplate.setExchange("exchange");
            rabbitTemplate.setRoutingKey("topic.01");

            rabbitTemplate.convertAndSend(map);
        }catch (Exception e){
            e.printStackTrace();
            log.error("发送对象消息发生异常： ", e.getMessage());
        }
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
     log.info("消息id:" + correlationData.getId());
        if (b) {
            log.info("消息发送确认成功");
        } else {
            log.error("消息发送确认失败:" + b);
        }

    }
}
